package org.xq.softcup.mq.serialize.impl;


import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.xq.softcup.mq.serialize.Serializer;
import org.xq.softcup.mq.util.XQRpcException;

import java.io.IOException;

public class JacksonSerializer extends Serializer {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public <T> byte[] serialize(T obj) {
        try {
            return objectMapper.writeValueAsBytes(obj);
        } catch (JsonProcessingException e) {
            throw new XQRpcException(e);
        }
    }

    public <T> Object deserialize(byte[] bytes, Class<T> clazz) {
        try {
            return objectMapper.readValue(bytes, clazz);
        } catch (JsonParseException e) {
            throw new XQRpcException(e);
        } catch (JsonMappingException e) {
            throw new XQRpcException(e);
        } catch (IOException e) {
            throw new XQRpcException(e);
        }
    }
}
